package com.ruoyi.product.service.impl;

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Value;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.product.mapper.GoodsCategoryMapper;
import com.ruoyi.product.domain.GoodsCategory;
import com.ruoyi.product.service.IGoodsCategoryService;

/**
 * 商品分类Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-07-04
 */
@Service
public class GoodsCategoryServiceImpl implements IGoodsCategoryService 
{
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private GoodsCategoryMapper goodsCategoryMapper;




    @Value("${cache.db.prefix:dbstore}")
    private String prefix;

    @Value("${cache.db.domain.goodsCategory.useCache:false}")
    private boolean useCache;
    @Value("${cache.db.domain.goodsCategory.strict:true}")
    private boolean strict;
    @Autowired
    private RedisService redisCache;
    //单位分钟
        @Value("${cache.db.domain.goodsCategory.timeout:10}")
    private long cacheTimeout;
    protected String cacheKey(Long id) {
        return new StringBuilder(prefix).append(":goodsCategory:").append(id).toString();
    }

    protected void deleteObject(Long id) {
        if (useCache) {
            if (id != null) {
                String key = cacheKey(id);
                try {
                    redisCache.deleteObject(key);
                } catch (Exception e) {
                    logger.error("redis delete error ,key:{}", key, e);
                    if(strict){
                        throw e;
                    }
                }
            }
        }

    }

    protected void setCacheObject(GoodsCategory goodsCategory) {
        if (useCache) {
            if (goodsCategory != null && goodsCategory.getId() != null) {
                String key = cacheKey(goodsCategory.getId());
                try {
                    if (goodsCategory != null) {
                        redisCache.setCacheObject(key, goodsCategory, cacheTimeout, TimeUnit.MINUTES);
                    }
                } catch (Exception e) {
                    logger.error("redis set error ,key:{}", key, e);

                }
            }
        }
    }

    protected GoodsCategory getCacheObject(Long id) {
        if (useCache) {
            String key = cacheKey(id);
            try {
                return redisCache.getCacheObject(key);
            } catch (Exception e) {
                logger.error("redis get error ,key:{}", key, e);

            }
        }

        return null;
    }

    /**
     * 查询商品分类
     * 
     * @param id 商品分类ID
     * @return 商品分类
     */
    @Override
    public GoodsCategory selectGoodsCategoryById(Long id)
    {
        GoodsCategory  goodsCategory = getCacheObject(id);
        if (goodsCategory == null) {
            goodsCategory = goodsCategoryMapper.selectGoodsCategoryById(id);
            setCacheObject(goodsCategory);
        }
        return goodsCategory;

    }
    @Override
    public List<GoodsCategory> selectGoodsCategoryByIds(Long[] ids)
    {
        return goodsCategoryMapper.selectGoodsCategoryByIds(ids);
    }

    /**
     * 查询商品分类列表
     * 
     * @param goodsCategory 商品分类
     * @return 商品分类
     */
    @Override
    public List<GoodsCategory> selectGoodsCategoryList(GoodsCategory goodsCategory)
    {
        return goodsCategoryMapper.selectGoodsCategoryList(goodsCategory);
    }

    /**
     * 新增商品分类
     * 
     * @param goodsCategory 商品分类
     * @return 结果
     */
    @Override
    public int insertGoodsCategory(GoodsCategory goodsCategory)
    {

        goodsCategory.setCreateTime(DateUtils.getNowDate());
        try {
            return goodsCategoryMapper.insertGoodsCategory(goodsCategory);
        } finally {
            deleteObject(goodsCategory.getId());
        }
     }

    /**
     * 修改商品分类
     * 
     * @param goodsCategory 商品分类
     * @return 结果
     */
    @Override
    public int updateGoodsCategory(GoodsCategory goodsCategory)
    {
        goodsCategory.setUpdateTime(DateUtils.getNowDate());
        try {
            return goodsCategoryMapper.updateGoodsCategory(goodsCategory);
        } finally {
            deleteObject(goodsCategory.getId());

        }
    }

    /**
     * 批量删除商品分类
     * 
     * @param ids 需要删除的商品分类ID
     * @return 结果
     */
    @Override
    public int deleteGoodsCategoryByIds(Long[] ids)
    {
        try {
            return goodsCategoryMapper.deleteGoodsCategoryByIds(ids);
        } finally {
            if (ids != null) {
                for (Long id : ids) {
                    deleteObject(id);

                }
            }
        }

    }

    /**
     * 删除商品分类信息
     * 
     * @param id 商品分类ID
     * @return 结果
     */
    @Override
    public int deleteGoodsCategoryById(Long id)
    {
        try {
            return goodsCategoryMapper.deleteGoodsCategoryById(id);
        } finally {
            deleteObject(id);
        }
    }

   /**
    * 构建前端所需要树结构
    * 
    * @param goodsCategorys 部门列表
    * @return 树结构列表
    */
    @Override
    public List<GoodsCategory> buildGoodsCategoryTree(List<GoodsCategory> goodsCategorys)
    {
        List<GoodsCategory> returnList = new ArrayList<GoodsCategory>();
        List<Long> tempList = new ArrayList<Long>();
        for (GoodsCategory goodsCategory : goodsCategorys)
        {
            
            tempList.add(goodsCategory.getId());
        }
        for (Iterator<GoodsCategory> iterator = goodsCategorys.iterator(); iterator.hasNext();)
        {
            GoodsCategory goodsCategory = (GoodsCategory) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(goodsCategory.getParentId()))
            {
                recursionFn(goodsCategorys, goodsCategory);
                returnList.add(goodsCategory);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = goodsCategorys;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param goodsCategorys 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildGoodsCategoryTreeSelect(List<GoodsCategory> goodsCategorys)
    {
        List<GoodsCategory> goodsCategoryTrees = buildGoodsCategoryTree(goodsCategorys);
        return goodsCategoryTrees.stream().map(this::toTreeSelect).collect(Collectors.toList());
    }
    protected TreeSelect toTreeSelect(GoodsCategory object){
        TreeSelect result= new TreeSelect();
        result.setId(object.getId());
        result.setLabel(object.getName());
        List<GoodsCategory>childeren=   (List<GoodsCategory>)object.getChildren();
        result.setChildren(childeren.stream().map(this::toTreeSelect).collect(Collectors.toList()));
        return result;
    }
    /**
     * 递归列表
     */
    private void recursionFn(List<GoodsCategory> list, GoodsCategory t)
    {
        // 得到子节点列表
        List<GoodsCategory> childList = getChildList(list, t);
        t.setChildren(childList);
        for (GoodsCategory tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }
    /**
   * 得到子节点列表
   */
    private List<GoodsCategory> getChildList(List<GoodsCategory> list, GoodsCategory t)
    {
        List<GoodsCategory> tlist = new ArrayList<GoodsCategory>();
        Iterator<GoodsCategory> it = list.iterator();
        while (it.hasNext())
        {
            GoodsCategory n = (GoodsCategory) it.next();
            
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }
    /**
   * 判断是否有子节点
   */
    private boolean hasChild(List<GoodsCategory> list, GoodsCategory t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

}
